package com.controller;

import com.api.CommonResult;
import com.api.Commons;
import com.entity.*;
import com.entity.table.AddressTableDef;
import com.entity.table.OrdersTableDef;
import com.service.AddressService;
import com.service.OrderProductsService;
import com.service.OrdersService;
import com.service.ProductsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class ClientController {
    @Autowired
    AddressService addressService;

    @Autowired
    OrdersService ordersService;

    @Autowired
    OrderProductsService orderProductsService;

    @Autowired
    ProductsService productsService;

    @GetMapping("/address")
    public String address(HttpServletRequest request, ModelMap model){
        HttpSession session =request.getSession();
        Users user = (Users) session.getAttribute("user");
        if(user == null){
            return "client/login";
        }
        Address fAddress = addressService.queryChain().where(AddressTableDef.ADDRESS.USER_ID.eq(user.getId())).one();
        model.addAttribute("address",fAddress);
        return "client/address";
    }
    @PostMapping("/address/update")
    public String updateAddress(Address fAddress , ModelMap model,HttpServletRequest request){
        HttpSession session =request.getSession();
        Users user = (Users) session.getAttribute("user");
        if(user == null){
            return "client/login";
        }
        fAddress.setUserId(user.getId());
        model.addAttribute("address",fAddress);
        addressService.saveOrUpdate(fAddress);
        return "client/address";
    }
    @GetMapping("/user")
    public String user_center_info(HttpServletRequest request, ModelMap model){
        HttpSession session =request.getSession();
        Users user = (Users) session.getAttribute("user");
        if(user == null){
            return "client/login";
        }
        List<Orders> ordersList=ordersService.queryChain().where(OrdersTableDef.ORDERS.USER_ID.eq(user.getId())).withRelations().list();
        model.addAttribute("users",user);
        model.addAttribute("address",ordersList);
        return "client/user";
    }
    @PostMapping("placeOrder")
    @ResponseBody
    @Transactional
    public CommonResult placeOrder(Products products,HttpServletRequest request){
        try{
            HttpSession session =request.getSession();
            Users user = (Users) session.getAttribute("user");
            Address fAddress =addressService.queryChain().where(AddressTableDef.ADDRESS.USER_ID.eq(user.getId())).one();
            if(fAddress == null){
                return CommonResult.failed("/address");
            }
            Orders fOrder = Orders.builder()
                    .status("配送中")
                    .orderDate(Commons.nowDate())
                    .userId(user.getId())
                    .totalAmount(products.getPrice().multiply(new BigDecimal(products.getQuantity())))
                    .build();
            ordersService.save(fOrder);
            OrderProducts orderProducts = OrderProducts.builder().orderId(fOrder.getId())
                    .productId(products.getId())
                    .quantity(products.getQuantity())
                    .orderId(fOrder.getId())
                    .build();
            orderProductsService.save(orderProducts);
        }
        catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return CommonResult.failed("/login");
        }
        return CommonResult.success("成功提交订单");
    }
    @GetMapping("/orderList")
    public String orderList(HttpServletRequest request, ModelMap model){
        HttpSession session =request.getSession();
        Users user = (Users) session.getAttribute("user");
        if(user == null){
            return "client/login";
        }
        List<Orders> ordersList=ordersService.queryChain().where(OrdersTableDef.ORDERS.USER_ID.eq(user.getId())).withRelations().list();
        model.addAttribute("orderList",ordersList);
        return "client/order-list";
    }
    @GetMapping("/orderSuccess")
    public String orderSuccess(HttpServletRequest request,ModelMap model){return "client/order-success";}

    @GetMapping("logout")
    public String logout(HttpSession httpSession){
        httpSession.removeAttribute("user");
        return "client/login";
    }

}
